<template>
  <el-card class="box-card">
    <!-- 查询表单 -->
    <el-form :inline="true" :rules="fromDatabaserules" :model="formInline" ref="formInline" class="demo-form-inline">
      <el-form-item label="源数据库地址" prop="s_address">
        <el-input v-model="formInline.s_address" placeholder="数据库地址"></el-input>
      </el-form-item>
      <el-form-item label="源数据库类型" style="width: 15%;">
        <el-select v-model="formInline.s_types" placeholder="MySQL" style="width: 100px;">
          <el-option label="MySQL" value="MySQL"></el-option>
          <!--el-option label="Oracle" value="Oracle"></el-option-->
        </el-select>
      </el-form-item>
      <el-form-item label="账号" prop="s_user">
        <el-input v-model="formInline.s_user" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="s_passwd">
        <el-input v-model="formInline.s_passwd" placeholder="密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="端口"  style="width: 10%;">
        <el-input v-model="formInline.s_port" placeholder="3306" style="width: 100px;"></el-input>
      </el-form-item>

      <el-form-item label="目的数据库地址" prop="d_address">
        <el-input v-model="formInline.d_address" placeholder="数据库地址"></el-input>
      </el-form-item>
      <el-form-item label="目的数据库类型"  style="width: 15%;" >
        <el-select v-model="formInline.d_types" placeholder="MySQL" style="width: 100px;">
          <el-option label="MySQL" value="MySQL"></el-option>
          <!--el-option label="Oracle" value="Oracle"></el-option-->
        </el-select>
      </el-form-item>
      <el-form-item label="账号" prop="d_user">
        <el-input v-model="formInline.d_user" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="d_passwd">
        <el-input v-model="formInline.d_passwd" placeholder="密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="端口" style="width: 10%;">
        <el-input v-model="formInline.d_port" placeholder="3306" style="width: 100px;"></el-input>
      </el-form-item>
    </el-form>
    <!-- 查询按钮 -->
    <el-form>
      <el-form-item class="op-btn">
        <el-button type="primary" @click="submitForm(formInline),centerDialogVisible = false"
          v-loading.fullscreen.lock="fullscreenLoading">查 询</el-button>
        <el-button type="info" @click="resetForm(formInline)">重 置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询数据返回弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="40%"
      center>
      <!--el-table :data="ResultDataForm">
        <el-table-column align="center" label="表" prop="table" />
        <el-table-column align="center" label="字段" prop="feilds" />
      </el-table-->
      <!-- 数据穿梭框 -->
      <tree-transfer :title="title" node-key="id" :pid="parent_id" :from_data='fromData' :to_data='toData' ref="choiceFromdata" :defaultProps="{label:'label'}"
      @add-btn='add' @remove-btn='remove' :mode='mode' height='500px' :button_text="['添加','移除']" filter>
      </tree-transfer>
      <span style="margin-top: 10px;">
        <el-select v-model="value" placeholder="数据量" style="width: 15%;">
          <el-option
            v-for="item in limit"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
        <el-button type="primary" @click="handRunSubmit">执 行</el-button>
      </span>
    </el-dialog>

    <!-- 任务列表 -->
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      style="margin-top: 20px;"
    >
      <el-table-column align="center" label="任务ID" prop="t_taskid" />
      <el-table-column align="center" label="任务开始时间" prop="t_starttime" />
      <el-table-column align="center" label="任务结束时间" prop="t_endtime" />
      <el-table-column align="center" label="任务状态" prop="t_status" />
      <el-table-column align="center" label="查询信息" >
        <template slot-scope="scope">
          <el-tooltip content="查询信息" placement="top">
            <el-button type="info" size="mini" icon="el-icon-document" circle @click="handleDatabaseClick(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="执行结果" >
        <template slot-scope="scope">
          <el-tooltip content="执行信息" placement="top">
            <el-button type="info" size="mini" icon="el-icon-document" circle @click="handleResClick(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查询信息展示 -->
    <el-dialog title="查询信息"
    :visible.sync="showdbinfo"
    width="40%">
      <json-viewer :value="dbinfojson" :expand-depth="5" copyable boxed sort /> </json-viewer>
    </el-dialog>
    <!-- 执行详情展示 -->
    <el-dialog title="执行信息"
    :visible.sync="show"
    width="40%">
      <json-viewer :value="dbjson" :expand-depth="5" copyable boxed sort /> </json-viewer>
    </el-dialog>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count">
      </el-pagination>
  </el-card>




</template>

<script>
  // 导入包
  import treeTransfer from 'el-tree-transfer'
  import { getDatabaseInfo, createDatabaseInfo, createRunSqlTask, getRunSqlTask } from '@/api/tmtask'
  import JsonViewer from 'vue-json-viewer'

  export default {
    // 数据穿梭框自定义信息
    props: {
        // el-tree node-key 必须唯一
      node_key: {
        type: String,
        default: "id"
      },
        // 自定义 pid参数名，因为后端给的参数名为parentId
      pid: {
        type: String,
        default: "parent_id"
      },
      defaultProps: {

      }
    },
    // 数据集
    data() {
      return {
        // 查询表单
        formInline: {
          s_address: '',
          s_types: 'MySQL',
          s_user: '',
          s_passwd: '',
          s_port: '3306',
          d_address: '',
          d_types: 'MySQL',
          d_user: '',
          d_passwd: '',
          d_port: '3306'
        },
        // 字段验证
        fromDatabaserules: {
          s_address: [{ required: true, message: '源数据库地址不能为空', trigger: 'blur' }],
          // s_types: [{ required: true, message: '请输入源数据库地址', trigger: 'blur' }],
          s_user: [{ required: true, message: '源数据库用户不能为空', trigger: 'blur' }],
          s_passwd: [{ required: true, message: '源数据库密码不能为空', trigger: 'blur' }],
          // s_port: [{ required: true, message: '请输入源数据库端口', trigger: 'blur' }],
          d_address: [{ required: true, message: '目的数据库地址不能为空', trigger: 'blur' }],
          // d_types: [{ required: true, message: '请输入源数据库地址', trigger: 'blur' }],
          d_user: [{ required: true, message: '目的数据库用户不能为空', trigger: 'blur' }],
          d_passwd: [{ required: true, message: '目的数据库密码不能为空', trigger: 'blur' }],
          // d_port: [{ required: true, message: '请输入源数据库地址', trigger: 'blur' }],
        },
        // 任务列表数据
        list: [],
        show: false,
        showdbinfo: false,
        dbjson: [],
        dbinfojson: {},
        // 分页
        count: 0,
        params: {
          page: 1,
          page_size: '',
        },
        // 执行数据数量
        limit: [{
          value: "1000",
          label: "1000"
        }],
        value: '1000',
        // 弹窗数据
        mode: "transfer", // transfer addressList
        title: ["源数据","目标数据"],
        parent_id: 'parent_id',
        fromData:[],
        toData: [],
        fullscreenLoading: false,
        centerDialogVisible: false,
        choiceData: "",
        runFromdata:[],

      };
    },
    // 任务列表查询执行
    created() {
      this.fetchData()
    },
    methods: {
      // 清洗选择数据函数
      convertToTreedata(data){
        //console.log(data, '数据构造........')
        var returnData = [];
        //遍历数据
        for(var i = 0; i < data.length; i++){
          for (var iw = 0; iw <data[i].children.length; iw++){
            for (var it = 0; it < data[i].children[iw].children.length; it++){
              var tempObj = data[i].children[iw].children[it].children
              // console.log(tempObj)
              returnData.push(tempObj)
            }
          }
        }
        return returnData;
      },
      // 查询按钮
      submitForm(formInline) {
        this.$refs.formInline.validate((valid) =>{
          if (valid) {
            // console.log(valid)
            createDatabaseInfo(this.formInline).then(res => {
              this.fullscreenLoading = true;
              if ( res["code"] === "200" ) {
                this.$message({
                  message: '查询成功~',
                  type: 'success'
                }),
                this.centerDialogVisible = true;
                this.fromData = res["results"]
                this.fromData.forEach(item =>{
                  item.parent_id = 0
                })
              } else if ( res["code"] === "400" ) {
                this.$message({
                  message: "查询失败~",
                  type: 'error'
                }),
                this.centerDialogVisible = false;
                this.fullscreenLoading = false;
              }
              setTimeout(() => {
                this.fullscreenLoading = false;
              }, 2000);
            })
          } else {
           // console.log('error submit!!');
            return false;
          }

        })
      },
      // 重置按钮
      resetForm(formInline) {
        this.$refs.formInline.resetFields()
      },
      // 任务列表数据
      fetchData() {
        getRunSqlTask(this.params).then(response => {
          this.list = response.results;
          this.count = response.count
          // console.log(response.results)
        })
      },
    // 监听pagesize改变的事件
      handleSizeChange(newSize) {
        this.params.page_size = newSize
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.params.page = 1
        this.params.page = val
        this.fetchData()
      },
      // 弹窗
      // 监听穿梭框组件添加
      add(fromData,toData,obj){
        // console.log("fromData:", fromData);
        // console.log(toData);
        // this.toData = toData
        var rest = this.convertToTreedata(toData)
        this.choiceData = rest
        // console.log(rest)
      },
      // 监听穿梭框组件移除
      remove(fromData,toData,obj){
        // console.log("fromData:", fromData);
        // console.log("toData:", toData);
        // console.log("obj:", obj);
      },
      // 执行按钮
      handRunSubmit(){
        this.runFromdata = this.formInline
        this.runFromdata["data"] = this.choiceData
        this.runFromdata["limit"] = this.value
        // console.log(this.choiceData)
        // console.log(this.runFromdata)
        createRunSqlTask(this.runFromdata).then(res =>{
          // console.log(res)
          // this.list = res
          // console.log(res)
          // var msg = res["msg"]
          console.log(res)
          if ( res["code"] === "200" ) {
            this.$message({
              message: "执行成功~",
              type: 'success'
            })
          } else if ( res["code"] === "400" ) {
            this.$message({
              message: "执行失败~",
              type: 'error'
            })
          } else if ( res["code"] === "201" ) {
            this.$message({
              message: "执行结果保存失败~",
              type: 'error'
            })
          }
        })
        window.location.reload()
      },
      // 关闭按钮
      handleClose(){
        this.centerDialogVisible=false,
        window.location.reload()
      },
      // 查看查询详情
      handleDatabaseClick(row) {
        this.showdbinfo = true
        this.dbinfojson = row.database
      },
      // 查看执行详情
      handleResClick(row) {
        // console.log(row.t_dbinfo)
        this.show = true
        this.dbjson = row.t_dbinfo
      }
    },
    components:{ treeTransfer,JsonViewer } // 注册
  }
</script>

<style lang="scss" scoped>
  .demo-form-inline {
    margin-left: 20px;
  }
  .demo-form-inline .el-form-item {
    margin-left: 20px;
    width: 350px;
  }

  .op-btn {
    margin-left: 35%;
    margin-top: 20px;
  }
</style>
